package oop.controller.api.topic;

import java.util.List;

import oop.controller.api.APIAction;
import oop.data.TopicInfo;
import oop.db.dao.TopicInfoDAO;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

public class AjaxSearchAction extends APIAction {

	@Override
	public Object performImpl() throws Exception {
		String query = request.getParameter("query");
		String format = request.getParameter("format");
		List<TopicInfo> topicInfos = TopicInfoDAO.fetchByNameIgnoreCase("%"
				+ query + "%");

		JsonObject result = new JsonObject();
		result.addProperty("query", query);
		JsonArray suggestions = new JsonArray();
		result.add("suggestions", suggestions);
		JsonArray data = new JsonArray();
		result.add("data", data);
		for (TopicInfo info : topicInfos) {
			String suggestion = info.getName();
			if ("qcount".equals(format)) {
				suggestion += " (" + info.getQuestionCount() + ")";
			}
			suggestions.add(new JsonPrimitive(suggestion));
			data.add(new JsonPrimitive(info.getId()));
		}
		return result;
	}

}
